// <com.woyouqiu.Copyright>
// --------------------------------------------------------------
// <copyright>上海有求网络科技有限公司 2015</copyright>
// <Solution>Vecen.BangChuang</Solution>
// <Project>Vecen.BangChuang.Application</Project>
// <FileName>ClassAppService.cs</FileName>
// <CreateTime>2017-05-05 0:01</CreateTime>
// <Author>何苗</Author>
// <Email>hemiao@woyouqiu.com</Email>
// <log date="2017-05-05 0:01" version="00001">创建</log>
// --------------------------------------------------------------
// </com.woyouqiu.Copyright>

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.UI;
using Vecen.BangChuang.BangChuang.Classes.Dtos;

namespace Vecen.BangChuang.BangChuang.Classes {
    /// <summary>
    /// 微课堂操作
    /// </summary>
    [AbpAuthorize]
    public class ClassAppService: BangChuangAppServiceBase, IClassAppService {
        private readonly IRepository<MicroClass> _microClassRepository;
        private readonly IRepository<ClassGroup> _classGroupRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="microClassRepository"></param>
        /// <param name="classGroupRepository"></param>
        public ClassAppService(IRepository<MicroClass> microClassRepository,
            IRepository<ClassGroup> classGroupRepository) {
            _microClassRepository = microClassRepository;
            _classGroupRepository = classGroupRepository;
        }

        /// <summary>
        /// 获得指定组别的所有课程
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ListResultDto<MicroClassListDto>> GetClassesAsync(GetClassesRequestDto input) {
            var query = _microClassRepository.GetAll().Where(c => c.GroupId == input.GroupId);
            var entities = await Task.Run(() => query.ToList());
            var dtos = entities.MapTo<List<MicroClassListDto>>();
            foreach(var dto in dtos) {
                dto.AudioId = await AttachmentManager.GetIdAsync(MicroClass.ClassVideoAttachmentType, dto.Id);
                dto.AvatarId = await AttachmentManager.GetIdAsync(MicroClass.ClassVideoThumbnailAttachmentType, dto.Id);
            }
            return new ListResultDto<MicroClassListDto>(dtos);
        }

        /// <summary>
        /// 根据ID获得课程明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<MicroClassDetailDto> GetByIdAsync(int id) {
            var entity = await _microClassRepository.FirstOrDefaultAsync(id);
            var dto = entity.MapTo<MicroClassDetailDto>();
            dto.AvatarId = await AttachmentManager.GetIdAsync(MicroClass.ClassVideoThumbnailAttachmentType, id);
            dto.AudioId = await AttachmentManager.GetIdAsync(MicroClass.ClassVideoAttachmentType, id);
            return dto;
        }

        /// <summary>
        /// 上传课程
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UploadClassAsync(ClassUploadInputDto input) {
            var microClass = input.MapTo<MicroClass>();
            var id = await _microClassRepository.InsertAndGetIdAsync(microClass);
            await AttachmentManager.UpdateObjectIdAsync(MicroClass.ClassVideoAttachmentType, input.AttachmentIds, id);
            await AttachmentManager.DelAttachmentAsync(MicroClass.ClassVideoAttachmentType, input.DelAttachmentIds);

            await AttachmentManager.UpdateObjectIdAsync(MicroClass.ClassVideoThumbnailAttachmentType,
                input.ThumbnailAttachmentIds, id);
            await AttachmentManager.DelAttachmentAsync(MicroClass.ClassVideoThumbnailAttachmentType,
                input.ThumbnailDelAttachmentIds);
        }

        /// <summary>
        /// 获得课程修改对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ClassUploadInputDto> GetClassEditDtoAsync(int id) {
            var microClass = await _microClassRepository.FirstOrDefaultAsync(id);
            var dto = new ClassUploadInputDto();
            if(microClass == null) {
                throw new UserFriendlyException("请求出错!", "要修改的课程不存在!");
            }
            dto.AttachmentIds = await AttachmentManager.GetIdsAsync(MicroClass.ClassVideoAttachmentType, id);
            dto.ThumbnailAttachmentIds =
                await AttachmentManager.GetIdsAsync(MicroClass.ClassVideoThumbnailAttachmentType, id);
            dto.DelAttachmentIds = new List<int>();
            dto.ThumbnailDelAttachmentIds = new List<int>();

            dto.ClassTime = microClass.ClassTime;
            dto.GroupId = microClass.GroupId;
            dto.Title = microClass.Title;
            dto.Description = microClass.Description;

            return dto;
        }

        /// <summary>
        /// 删除课程
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteClassAsync(int id) {
            await _microClassRepository.DeleteAsync(id);
            await AttachmentManager.DelAttachmentWithObjectIdAsync(MicroClass.ClassVideoAttachmentType, id);
            await AttachmentManager.DelAttachmentWithObjectIdAsync(MicroClass.ClassVideoThumbnailAttachmentType, id);
        }

        /// <summary>
        /// 获得课程分组
        /// </summary>
        /// <returns></returns>
        public async Task<ListResultDto<ClassGroupOutDto>> GetClassGroupsAsync() {
            var entities = await Task.Run(() => _classGroupRepository.GetAllIncluding(c => c.Classes).ToList());
            var dtoList = new List<ClassGroupOutDto>();
            foreach(var entity in entities) {
                var dto = entity.MapTo<ClassGroupOutDto>();
                if(entity.Classes.Count > 0) {
                    dto.StartDate = entity.Classes.Min(c => c.ClassTime);
                    dto.EndDate = entity.Classes.Max(c => c.ClassTime);
                }

                dto.ClassCount = entity.Classes.Count;
                dto.AvatarId =
                    await AttachmentManager.GetIdAsync(ClassGroup.ClassGroupThumbnailAttachmentType, entity.Id);
                dtoList.Add(dto);
            }
            return new ListResultDto<ClassGroupOutDto>(dtoList);
        }

        /// <summary>
        /// 添加/修改课程分组
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SaveClassGroupAsync(ClassGroupInputDto input) {
            var exists =
                await _classGroupRepository.FirstOrDefaultAsync(
                    c => c.GroupName == input.GroupName && c.Id != input.Id);
            if(exists != null) {
                throw new UserFriendlyException("请求失败！", "该课程名称已经存在！");
            }
            var entity = input.MapTo<ClassGroup>();
            var id = await _classGroupRepository.InsertOrUpdateAndGetIdAsync(entity);

            await AttachmentManager.UpdateObjectIdAsync(ClassGroup.ClassGroupThumbnailAttachmentType,
                input.AttachmentIds, id);
            await AttachmentManager.DelAttachmentAsync(ClassGroup.ClassGroupThumbnailAttachmentType,
                input.DelAttachmentIds);
        }

        /// <summary>
        /// 获得课程分组修改对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ClassGroupInputDto> GetClassGroupForEditAsync(int id) {
            var dto = new ClassGroupInputDto();
            var entity = await _classGroupRepository.FirstOrDefaultAsync(id);
            if(entity == null) {
                dto.AttachmentIds = new List<int>();
                dto.DelAttachmentIds = new List<int>();
            } else {
                dto.AttachmentIds =
                    await AttachmentManager.GetIdsAsync(ClassGroup.ClassGroupThumbnailAttachmentType, id);
                dto.DelAttachmentIds = new List<int>();
                dto.Description = entity.Description;
                dto.GroupName = entity.GroupName;
                dto.Id = id;
            }
            return dto;
        }

        /// <summary>
        /// 删除课程分组
        /// </summary>
        /// <param name="id">分组ID</param>
        /// <returns></returns>
        public async Task DeleteClassGroupAsync(int id) {
            var exists = await Task.Run(() => _microClassRepository.GetAll().Any(c => c.GroupId == id));
            if(exists) {
                throw new UserFriendlyException("请求失败！", "该课程下面还有课时未删除，请删除后再操作！");
            }
            await _classGroupRepository.DeleteAsync(id);
            await AttachmentManager.DelAttachmentWithObjectIdAsync(ClassGroup.ClassGroupThumbnailAttachmentType, id);
        }
    }
}